package com.bigtotoro.shuiyincamera.video;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.view.ContextThemeWrapper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;
import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.MainActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.adapter_can_moved.ItemDragHelperCallback;
import com.bigtotoro.shuiyincamera.adapter_can_moved.OnDragVHListener;
import com.bigtotoro.shuiyincamera.adapter_can_moved.OnItemMoveListener;
import com.bigtotoro.shuiyincamera.editimage.utils.CompatResourceUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.editimage.view.SpaceItemDecoration;
import com.bigtotoro.shuiyincamera.image.RemoveWaterMarkActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.FileUtils;
import com.bigtotoro.shuiyincamera.util.ModelSingle;
import com.bigtotoro.shuiyincamera.util.MyMaths;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoItem;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.trim.VideoTrimmerActivity;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import java.util.List;

import io.microshow.rxffmpeg.RxFFmpegCommandList;
import io.microshow.rxffmpeg.RxFFmpegInvoke;
import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

//视频拼接

public class VideoConcatActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "video-concat";
    private FrameLayout frameLayout;
    private VideoView videoView;

    int frameWidth, frameHeight;
    int videoWidth, videoHeight, videoRotation, videoDuration;
    //    private String path = "/storage/emulated/0/dakashuiyin/video/slice/1553506380742.mp4"; // 3s
    private String finalOut;
    private float scale;
    private float videoX, videoY;
    private ProgressDialog mProgressDialog;

    private List<VideoItem> selectList7;
    private MediaPlayer.OnPreparedListener OnPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            VideoItem video = dataList.get(currentPlayIndex);
            videoWidth = video.getWidth();
            videoHeight = video.getHeight();
            videoDuration = mediaPlayer.getDuration();
            Log.d("main", "setOnPreparedListener duration " + videoDuration);

            videoView.start();
            //根据列表循环播放
//            mediaPlayer.setLooping(true); //循环播放

            frameWidth = frameLayout.getWidth();
            frameHeight = frameLayout.getHeight();
            Log.d(TAG, "frame" + frameWidth + ":" + frameHeight); //1080:1500
            Log.d(TAG, "video" + videoWidth + ":" + videoHeight); //1920:1080
//                Toast.makeText(MainActivity.this, frameWidth+":"+frameHeight, Toast.LENGTH_SHORT).show();

            float xScale = (float) frameWidth / videoWidth;
            float yScale = (float) frameHeight / videoHeight;

            //For Center Crop use the Math.max to calculate the scale
            //float scale = Math.max(xScale, yScale);
            //For Center Inside use the Math.min scale.
            //I prefer Center Inside so I am using Math.min
            scale = Math.min(xScale, yScale);

//            float scaledWidth = scale * videoWidth;
//            float scaledHeight = scale * videoHeight;
            float scaledWidth =  videoWidth;
            float scaledHeight =  videoHeight;
            Log.i("视频拼接","videoWidth==="+videoWidth+" ,  videoHeight===" + videoHeight);

            //Set the new size for the VideoView based on the dimensions of the video
            ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
            layoutParams.width = (int) scaledWidth;
            layoutParams.height = (int) scaledHeight;
            videoView.setLayoutParams(layoutParams);

            videoView.invalidate(); //刷新界面
            videoX = (frameWidth - layoutParams.width) / 2;
            videoY = (frameHeight - layoutParams.height) / 2;

            Log.d(TAG, "scaledWidth " + scaledWidth + " scaledHeight " + scaledHeight);
            Log.d(TAG, "video after set params");
            Log.d(TAG, "videoView" + videoView.getWidth() + ":" + videoView.getHeight());
            Log.d(TAG, "videoView getx " + videoView.getX() + " and getY " + videoView.getY());
        }
    };
    private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            //播放完成后，从列表中获取播放地址
            currentPlayIndex++;
            if (currentPlayIndex >= dataList.size()){
                currentPlayIndex = 0;
            }

            VideoItem localMedia = dataList.get(currentPlayIndex);
            selectData.clear();
            selectData.add(localMedia);
            adapter.notifyDataSetChanged(); //更新UI

            String videoPath = localMedia.getPath();
            Log.i("视频拼接","视频播放完成，currentPlayIndex==="+currentPlayIndex + "videoPath==="+videoPath);
            videoView.setVideoURI(Uri.parse(videoPath));
            videoView.start();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_splice);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));
        Log.i("视频拼接", "执行了 onCreate ");

        //添加友盟事件统计
        MyUtils.addUmengEvent(VideoConcatActivity.this,"video_concat","视频拼接");
        initBase();

        findViewById(R.id.btn_save).setOnClickListener(this);
        videoView = findViewById(R.id.video);
        if (ModelSingle.getInstance().getMode2() != null) {
            Log.i("视频拼接", "ModelSingle 不为空 " );
            selectList7 = (List<VideoItem>) ModelSingle.getInstance().getMode2();
            //设置数据

            if (selectList7 != null && selectList7.size() > 0) {

                dataList.clear();
                dataList.addAll(selectList7);
                Log.i("视频拼接", "dataList。size==== " + dataList.size());

                initRecycleView();

                //不是设置第一个选中，是播放哪个，哪个选中
                //需要监听视频播放状态

                currentPlayIndex = 0;
                setVideoView(currentPlayIndex);
            }

        }else {
            Log.i("视频拼接", "ModelSingle 为空 " );
        }

        frameLayout = findViewById(R.id.frame);
        VideoUtil.checkVideoDir();
        videoView.setOnPreparedListener(OnPreparedListener);
        videoView.setOnCompletionListener(completionListener);
    }

    private RecyclerView recyclerView;    //全部视频列表（按日期分类）
    private RecyclerView itemRecycleview;   //每个日期下的视频列表
    private List<VideoItem> dataList = new ArrayList<>();
    private List<VideoItem> selectData = new ArrayList<>();
//    private SimpleAdapter3<LocalMedia> recycleAdapter = null;
    private DragAdapter adapter;

    private int currentEditPosition;

    private void initRecycleView() {
        recyclerView = findViewById(R.id.recyclerView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(VideoConcatActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);  //防止recycleview和srcollview滑动冲突，必须加不然无法顺畅滑动列表
        recyclerView.addItemDecoration(new SpaceItemDecoration(
                CompatResourceUtils.getDimensionPixelSize(this, R.dimen.space_10),
                CompatResourceUtils.getDimensionPixelSize(this, R.dimen.space_0)
        ));

        //绑定长按拖拽,交换的实现逻辑放在了BaseHeaderFooterAdapter中
        ItemDragHelperCallback callback = new ItemDragHelperCallback(){
            @Override
            public boolean isLongPressDragEnabled() {
                // 长按拖拽打开
                return true;
            }
        };
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recyclerView);

        adapter = new DragAdapter(this, dataList);
        recyclerView.setAdapter(adapter);
    }

    public class DragAdapter extends RecyclerView.Adapter<DragAdapter.DragViewHolder> implements OnItemMoveListener {
        private List<VideoItem> mItems;
//        final List<LocalMedia> selectData = new ArrayList<>();

        private LayoutInflater mInflater;

        public DragAdapter(Context context, List<VideoItem> items) {
            mInflater = LayoutInflater.from(context);
            this.mItems = items;
        }

        @Override
        public DragViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new DragViewHolder(mInflater.inflate(R.layout.item_recycle, parent, false));
        }

        @Override
        public void onBindViewHolder(DragViewHolder holder, int position) {
            if (selectData.contains(mItems.get(position))){
                holder.item.setSelected(true);
            }else {
                holder.item.setSelected(false);
            }

            holder.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int) v.getTag();
                    VideoItem local = mItems.get(position);
                    currentPlayIndex = position;

                    videoView.pause();
                    setVideoView(currentPlayIndex);

                }
            });
            holder.item.setTag(holder.getAdapterPosition());

            Bitmap bitmap = MyUtils.getVideoThumb(mItems.get(position).getPath());
            if (mItems.get(position).getPath() != null && bitmap != null) {
                holder.iv_photo.setImageBitmap(bitmap);
            }

            holder.btn_edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int) v.getTag();
                    currentEditPosition = position;
                    VideoItem localMedia1 = dataList.get(position);
                    //停止播放视频
                    videoView.pause();
                    videoView.stopPlayback();
                    //点击进入视频剪切界面
                    startActivityForResult(new Intent(VideoConcatActivity.this, VideoTrimmerActivity.class)
                                    .putExtra(VideoTrimmerActivity.VIDEO_PATH_KEY, localMedia1.getPath())
                                    .putExtra("mode", "splice_edit")
                                    .putExtra("position", position)
                            , REQUEST_CODE_SPLICE_EDIT
                    );
                }
            });
            holder.btn_edit.setTag(holder.getAdapterPosition());
        }

        @Override
        public int getItemCount() {
            return mItems.size();
        }

        @Override
        public void onItemMove(int fromPosition, int toPosition) {
            VideoItem item = mItems.get(fromPosition);
            mItems.remove(fromPosition);
            mItems.add(toPosition, item);
            notifyItemMoved(fromPosition, toPosition);
        }

        class DragViewHolder extends RecyclerView.ViewHolder implements OnDragVHListener {
            ImageView iv_photo;
            FrameLayout item;
            FrameLayout btn_edit;

            public DragViewHolder(View itemView) {
                super(itemView);
                iv_photo =  itemView.findViewById(R.id.iv_photo);
                item =  itemView.findViewById(R.id.item);
                btn_edit =  itemView.findViewById(R.id.btn_edit);
            }

            @Override
            public void onItemSelected() {
                itemView.setBackgroundColor(Color.LTGRAY);
            }

            @Override
            public void onItemFinish() {
                itemView.setBackgroundColor(0);
            }
        }
    }

    private String newpath = "";
    private static final int REQUEST_CODE_SPLICE_EDIT = 8399;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_SPLICE_EDIT) {
                if (intent != null && intent.getStringExtra("edit_path") != null) {
                    newpath = intent.getStringExtra("edit_path");
                    VideoItem item = dataList.get(currentEditPosition);
                    item.setPath(newpath);
                    dataList.set(currentEditPosition, item);
                    adapter.notifyDataSetChanged();
//                    recycleAdapter.notifyDataSetChanged();

                    videoView.start();
//                    setVideoView(dataList.get(0).getPath());

                }
            }
        }
    }

    private int currentPlayIndex = 0;
    private void setVideoView(int currentPlayIndex) {
        VideoItem localMedia = dataList.get(currentPlayIndex);
        selectData.clear();
        selectData.add(dataList.get(currentPlayIndex));
        adapter.notifyDataSetChanged();

        videoView.pause();
        videoView.stopPlayback();
        videoView.setVideoURI(Uri.parse(localMedia.getPath()));
        videoView.start();
        videoView.setOnPreparedListener(OnPreparedListener);
        videoView.setOnCompletionListener(completionListener);
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_save) {
            dialogList();
        }
    }

    private void dialogList() {
//        final String items[] = {"9:16(540x960手机视频)", "16:9(960x540)", "1:1(800x800)", "4:3(800x600)","自定义"};
        final String items[] = {"9:16(540x960手机视频)", "16:9(960x540)", "1:1(800x800)", "4:3(800x600)"};

        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
        builder.setTitle("选择视频导出尺寸");
//            builder.setIcon(R.mipmap.ic_launcher);
        // 设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                //添加友盟事件统计
                MyUtils.addUmengEvent(VideoConcatActivity.this,"video_concat_save","视频拼接保存");

                if (which == 0) {
                    new VideoAsyncTask().execute(540, 960);
                } else if (which == 1) {
                    new VideoAsyncTask().execute(960, 540);
                } else if (which == 2) {
                    new VideoAsyncTask().execute(800, 800);
                } else if (which == 3) {
                    new VideoAsyncTask().execute(800, 600);
                }
                else if(which == 4){

                }
            }
        });
        builder.create().show();
//            builder.setIcon(R.mipmap.ic_launcher);
        // 设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。



    }

    class VideoAsyncTask extends AsyncTask<Integer, Integer, Void> {
        int vW, vH;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(VideoConcatActivity.this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(100);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setTitle("正在处理");

            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            mProgressDialog.setProgress(values[0]);// 更新进度条的进度
        }

        @Override
        protected Void doInBackground(Integer... values) {
            String tempFile =  VideoUtil.VIDEO_TEMP_DIR+"/"+System.currentTimeMillis()+".txt";
            vW = values[0];
            vH = values[1];
            Log.d(TAG, "doInBackground "+vW+", "+vH);
            publishProgress(1);
            for (VideoItem video: dataList){
                String out = VideoUtil.VIDEO_TEMP_DIR+"/"+System.currentTimeMillis()+".mp4";
                String cmd = String.format("ffmpeg -y -i %s -vf scale='min(%d,iw)':min'(%d,ih)':force_original_aspect_ratio=decrease,pad=%d:%d:(ow-iw)/2:(oh-ih)/2 -b 2097k -r 30 -vcodec libx264 -preset superfast %s", video.getPath(), vW, vH, vW, vH, out);
//                String cmd = String.format("ffmpeg -y -i %s -vf scale='min(%d,iw)':min'(%d,ih)':force_original_aspect_ratio=decrease,pad=%d:%d:(ow-iw)/2:(oh-ih)/2 -preset superfast %s", video.getPath(), vW, vH, vW, vH, out);
                String[] command = cmd.split(" ");
                RxFFmpegInvoke.getInstance().runCommand(command, null);
                FileUtils.appendTxt(tempFile, String.format("file '%s'\r\n", out));
                publishProgress((dataList.indexOf(video)+1)*100/dataList.size());

            }

            finalOut = VideoUtil.VIDEO_OUT_DIR+"/"+System.currentTimeMillis()+".mp4";
            String cmd = String.format("ffmpeg -y -f concat -safe 0 -i %s -vcodec copy -acodec copy %s", tempFile, finalOut);
            String[] command = cmd.split(" ");
            RxFFmpegInvoke.getInstance().runCommand(command, null);
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            Log.i(TAG, "视频拼接完成");
            Toast.makeText(VideoConcatActivity.this, "处理完成", Toast.LENGTH_SHORT).show();
            MyArt art = new MyArt();
            art.setHeight(vH);
            art.setWidth(vW);
            art.setCreate_time(System.currentTimeMillis() + "");
            art.setPath(finalOut);
            art.setType(1);
            art.save();
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
//            FileUtil.ablumUpdate(VideoConcatActivity.this, art.getPath(),1);//更新相册
            Intent intent = new Intent(VideoConcatActivity.this, ShowMyArtsActivity.class);
            intent.putExtra(EXTRA_OUTPUT, finalOut);
            intent.putExtra("create_time", art.getTrueCreateTime());
            intent.putExtra("width", vW);
            intent.putExtra("height", vH);
            intent.putExtra("type", "1");
            startActivity(intent);
            finish();

        }
    }


//    private void resizeVideoView(View vRoot, int which){
//        int vMaxWidth = vRoot.getWidth();
//        ViewGroup.LayoutParams vParams = videoPlayer.getLayoutParams();
//        if (which == 0) {
////            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9);
//            vParams.width = vMaxWidth;
//            vParams.height = (int) (vMaxWidth*(9f/16f));
//            videoPlayer.setLayoutParams(vParams);
//        } else if (which == 1) {
////            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3);
//            vParams.width = vMaxWidth;
//            vParams.height = (int) (vMaxWidth*(3f/4f));
//            videoPlayer.setLayoutParams(vParams);
//        } else if (which == 2) {
////            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_CUSTOM);
////            GSYVideoType.setScreenScaleRatio(1f);
//            vParams.width = vMaxWidth;
//            vParams.height = vMaxWidth;
//            videoPlayer.setLayoutParams(vParams);
//        } else if (which == 3) {
////            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_CUSTOM);
////            GSYVideoType.setScreenScaleRatio(9f/16f);
//            vParams.width = (int) (screenWidth*(9f/16f));
//            vParams.height = vMaxWidth;
//            videoPlayer.setLayoutParams(vParams);
//        }
//    }



    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("VideoSplice2Activity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("VideoSplice2Activity");//统计页面
        MobclickAgent.onPause(this);
    }
}
